﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebMatrix.WebData;

namespace BuildServer
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
    {
        private static SimpleMembershipInitializer _initializer;
        private static object _initializerLock = new object();
        private static bool _isInitialized;

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // Ensure ASP.NET Simple Membership is initialized only once per app start
            LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
        }

        private class SimpleMembershipInitializer
        {
            public SimpleMembershipInitializer()
            {
                try
                {
                    WebSecurity.InitializeDatabaseConnection("WebSecurity", "UserProfile", "UserId", "UserName", autoCreateTables: true);

                    // make sure the 'Admin'-Role exists
                    if (!Roles.RoleExists("Admin")) {
                        Roles.CreateRole("Admin");
                    }
                    // make sure there is at least one 'Admin'-User
                    if (Roles.GetUsersInRole("Admin").Length == 0)
                    {
                        // Create 'Admin'-User
                        if (!WebSecurity.UserExists("Admin"))
                        {
                            WebSecurity.CreateUserAndAccount("Admin", "Admin", null, false);
                        }
                        // Assign 'Admin'-User to 'Admin'-Group
                        Roles.AddUserToRole("Admin", "Admin");
                    }

                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        }
    }
}